package com.corpdata.core.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class SystemExceptionHandler {
	@ModelAttribute
	public String newModel() {
		// System.out.println("==应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
		return null;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// System.out.println("==应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
	}

	@ExceptionHandler({ UnauthorizedException.class })
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ModelAndView processUnauthenticatedException(NativeWebRequest request, Exception e) {
		ModelAndView mv = new ModelAndView();
		String exceptionPage = "ExceptionPage/";
		if (e.getClass() == UnauthorizedException.class) {
			//没有权限异常
			exceptionPage += "unauthorized";
		} else {
			//系统代码异常
			exceptionPage += "500";
		}
		mv.addObject("ex", e);
		mv.setViewName(exceptionPage);
		return mv;
	}
}